<template>
  <div class="container">
    <el-row :gutter="20">
      <!-- 左侧患者列表 -->
      <el-col :span="6">
        <el-card class="patient-list-card">
          <template #header>
            <span>患者列表</span>
          </template>
          <el-input
              v-model="searchKey"
              placeholder="搜索患者姓名"
              clearable
              @keyup.enter="searchPatients"
          >
            <template #append>
              <el-button @click="searchPatients">搜索</el-button>
            </template>
          </el-input>
          <el-table
              :data="filteredList"
              @row-click="handleCurrentChange"
              highlight-current-row
              style="margin-top: 50px;"

          >
            <el-table-column prop="id" label="ID" width="50px" />
            <el-table-column prop="realname" label="患者姓名" />
            <el-table-column prop="casenumber" label="编号" />

          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧详情区域 -->
      <el-col :span="18">
        <el-card class="patient-detail-card">
          <template #header>
            <span>患者检验明细</span>
            <div class="action-buttons">
              <el-button
                  type="primary"
                  @click="executeSelected"
                  :disabled="!selectedCheckItems.length"
              >
                执行确认
              </el-button>
            </div>
          </template>

          <!-- 右上侧患者信息 -->
          <el-form  label-width="80px" class="info-form">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="病历号">
                  <el-input v-model="currentpatient.casenumber" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="患者姓名">
                  <el-input v-model="currentpatient.realname" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="年龄">
                  <el-input v-model="currentpatient.age" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="结算类别">
                  <el-input :value="getSettleTypeName(currentpatient.settleid)" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="午别">
                  <el-input v-model="currentpatient.noon" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="状态">
                  <el-input :value="getVisitState(currentpatient.visitstate)" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="看诊日期">
                  <el-input v-model="currentpatient.visitdate" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="开单医生">
                  <el-input :value="getDoctorName(currentpatient.userid)" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="身份证号">
                  <el-input v-model="currentpatient.idnumber" disabled />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <!-- 右下侧检验项目 -->
          <el-table
              :data="checktable"
              @selection-change="handleCheckSelectionChange"
              style="margin-top: 20px;"
              border
              stripe
          >
            <el-table-column type="selection" width="55" :selectable="checkSelectable"/>
            <el-table-column prop="name" label="检验名称" />
            <el-table-column prop="num" label="单价" />
            <el-table-column property="isurgent" label="是否紧急" >
              <template #default="scope">
              {{ scope.row.isurgent === 1 ? '加急' : scope.row.recordtype === 0 ? '正常':'正常' }}
              </template >
            </el-table-column>
            <el-table-column property="state" label="状态" >
              <template #default="scope">
                {{ scope.row.state === 0 ? '未开具' : scope.row.state === 1 ? '已开具':scope.row.state === 2 ? '已缴费':scope.row.state === 3 ? '已检查':scope.row.state === 4 ? '已完成':'未知' }}
              </template>
            </el-table-column>
            <el-table-column label="检查结果" width="100">
              <template #default="scope">
                <el-input
                    v-model="scope.row.result"
                    placeholder="输入结果"
                    size="small"
                    :disabled="scope.row.state !== 2"
                ></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed} from 'vue'
import axios from 'axios'
import {ElMessage, ElNotification} from 'element-plus'
import service from "@/utils/request.js";
import {useCounterStore} from "@/stores/counter.js";

// 状态管理
const getSettleTypeName = (id) => {
  const map = {
    1: '自费',
    2: '市医保',
  };
  return map[id] || '未知';
};
const getDoctorName = (userid) => {
  console.log("getDoctorName")
  if (!userlist.value || userlist.value.length === 0) return '未知';
  const doctor = userlist.value.find(item => item.id === userid);
  console.log(doctor)
  return doctor.realName || '未知'; // 返回医生姓名或'未知'
}
const getVisitState = (id) => {
  const map = {
    1: '未看诊',
    2: '已看诊',
  };
  return map[id] || '未知';
};
const patientDetail = reactive({
  caseNumber: '',
  realName: '',
  age: '',
  settleCategory: '',
  department: '',
  prescriptionStatus: '',
  chargeDate: '',
  doctorName: '',
  invoiceNo: ''
})
const counter = useCounterStore();
const checkItems = ref([])
const searchKey = ref('')
const selectedCheckItems = ref([])
const currentPatientId = ref(null)
let checktable=ref([])
let registlist=ref([])
let departmentlist=ref([])
let currentpatient=ref({})
let userlist=ref([])
let patientlist=ref([])
// API基础路径
function checkSelectable(row, index) {
  return row.state === 2; // 只有状态为0（未开具）的行才可选择
}
const apiBaseUrl = '/api/examine'
const filteredList = ref([]);

const fetchPatients = async () => {
  try {
    const res = await axios.get(`${apiBaseUrl}/patients`)
    patientList.value = res.data
  } catch (error) {
    console.error('获取患者列表失败:', error)
    ElMessage.error('获取患者列表失败')
  }
}

// 搜索患者
const searchPatients = () => {
  if (!searchKey.value) {
    filteredList.value=patientlist.value
    return
  }
  // 前端过滤
  const filtered = filteredList.value.filter(patient =>
      patient.realname.includes(searchKey.value)
  )
  filteredList.value = filtered
}

// 处理检验项目选择
const handleCheckSelectionChange = (val) => {
  selectedCheckItems.value = val
}

// 执行确认
function executeSelected()  {
  console.log(selectedCheckItems.value)
  selectedCheckItems.value.forEach(item => {
    item.checkoperid = counter.vo_user.value.id;
  });
  service.post("/check/checkcompleted",selectedCheckItems.value).then(
      res => {
        console.log("addapply")
        console.log(res.data)
        if(res){
          console.log("addapply：true")
          updatedata()
          ElNotification({
            title: '成功',
            message: `已提交检查`,
            type: 'success'
          });
        }
      }
  )
}

// 取消执行


// 填写结果
const saveResults = async () => {
  try {
    // 转换为后端需要的格式
    const results = selectedCheckItems.value.map(item => ({
      id: item.id,
      name: item.name,
      position: item.position,
      num: item.num,
      state: item.state === '未检' ? 1 : 2
    }))
    await axios.post(`${apiBaseUrl}/saveResults`, results)
    // 刷新检验项目列表
    const res = await axios.get(`${apiBaseUrl}/checks/${currentPatientId.value}`)
    checkItems.value = res.data
    selectedCheckItems.value = []
    ElMessage.success('结果保存成功')
  } catch (error) {
    console.error('保存结果失败:', error)
    ElMessage.error('保存结果失败')
  }
}
onMounted(()=>{
  console.log("钩子钩子")
  service.post("/register/listall").then(
      res=>{
        registlist.value=res.data
      }
  )

  service.post("/dept/list").then(
      res=>{
        console.log(res.data)
        departmentlist.value = res.data
      }
  )
  service.post("/user/list").then(
      res=>{
        console.log("user")
        console.log(res.data)
        userlist.value = res.data
      }
  )
})
function handleCurrentChange(row){
  currentpatient.value=row
  console.log(currentpatient.value)
  updatedata()
}

function updatedata(){
  console.log("updatedata")

  console.log("row")
  console.log(currentpatient)
  service.post("/check/listbyregistid?registid="+ currentpatient.value.id).then(
      res => {
        console.log("listbyregistid")
        console.log(res.data)
        checktable.value = res.data;
        console.log(checktable.value)
      }
  )
}

Promise.all([
  service.post("/register/listall"),
  service.post("/check/listpaid") // 后端已筛选state=3
])
    .then(([regRes, checkRes]) => {
      // 1. 将check数据转为Map，便于快速查找
      const checkMap = new Map(
          checkRes.data.map(check => [check.registid, check])
      );

      // 2. 筛选regist数据中存在于checkMap的记录
      filteredList.value = regRes.data.filter(reg =>
          checkMap.has(reg.id)
      );
      console.log("filteredList.value")
      console.log(filteredList.value)
      patientlist.value=filteredList.value
      console.log("filteredList.value")
    });
// 初始化加载患者列表


</script>

<style scoped>
.container {
  padding: 20px;
}

.patient-list-card {
  height: 100%;
}

.patient-detail-card {
  height: 100%;
}

.action-buttons {
  float: right;
}

.info-form {
  margin-top: 16px;
}
</style>